package com.vick.com;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.gen.tool.AlertDialog_PG;
import com.gen.tool.SoundPlayer;
import com.ouken.com.R;
import com.ouken.com.R.drawable;
import com.ouken.tool.ConnectServer;
import com.ouken.tool.MyApp;
import com.vick.tool.BitmapTool;
import com.vick.tool.DialogTool;
import com.vick.tool.MiscTool;

public class DrawingActivity extends Activity {
	private DrawingView dp_draw;
	private EditText et_word;
	private TextView tv_time;
	//MplayerTool mplayerTool;
	ImageButton ib_ok, ib_quit;
	ImageButton ib_black, ib_red, ib_blue, ib_yellow, ib_green, ib_pencil,
			ib_eraser, ib_clear, ib_small, ib_medium, ib_large;
	CountDownTimer countDown = new CountDownTimer(90000, 1000) {
		public void onTick(long millisUntilFinished) {
			tv_time.setText(Long.toString(millisUntilFinished / 1000));
		}

		public void onFinish() {
			new DrawingTimeoutTask().execute();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.drawing);
		//mplayerTool = new MplayerTool(this);
		countDown.start();

		/*----- Get screen components -----*/
		tv_time = (TextView) findViewById(R.id.drawingActivity_tv_time);
		ib_ok = (ImageButton) findViewById(R.id.drawingActivity_ib_ok);
		ib_quit = (ImageButton) findViewById(R.id.drawingActivity_ib_quit);
		ib_black = (ImageButton) findViewById(R.id.drawingActivity_ib_black);
		ib_red = (ImageButton) findViewById(R.id.drawingActivity_ib_red);
		ib_blue = (ImageButton) findViewById(R.id.drawingActivity_ib_blue);
		ib_yellow = (ImageButton) findViewById(R.id.drawingAcitvity_ib_yellow);
		ib_green = (ImageButton) findViewById(R.id.drawingActivity_ib_green);
		ib_pencil = (ImageButton) findViewById(R.id.drawingActivity_ib_pencil);
		ib_eraser = (ImageButton) findViewById(R.id.drawingActivity_ib_eraser);
		ib_clear = (ImageButton) findViewById(R.id.drawingActivity_ib_clear);
		ib_small = (ImageButton) findViewById(R.id.drawingActivity_ib_small);
		ib_medium = (ImageButton) findViewById(R.id.drawingActivity_ib_medium);
		ib_large = (ImageButton) findViewById(R.id.drawingActivity_ib_large);
		dp_draw = (DrawingView) findViewById(R.id.drawingActivity_dp_draw);
		et_word = (EditText) findViewById(R.id.drawingActivity_et_word);

		/*----- Click OK -----*/
		ib_ok.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SoundPlayer.playSound(R.raw.keypress_common);
				//mplayerTool.playButtonPressed(DrawingActivity.this);
				String word = et_word.getText().toString();
				word = word.trim();
				if (word.length() == 0 || !word.matches("[A-Za-z]+")) {
					DialogTool.showCustomMessage(DrawingActivity.this,
							"Word can't be blank and must contains only a-z");
				} else {
					saveImage();

				}
			}
		});
		ib_quit.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				SoundPlayer.playSound(R.raw.keypress_common);
				//mplayerTool.playButtonPressed(DrawingActivity.this);
				new QuitDrawingTask().execute();
			}
		});
		ib_black.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				SoundPlayer.playSound(R.raw.keypress_common);
				//mplayerTool.playButtonPressed(DrawingActivity.this);
				dp_draw.setPaintColor(Color.BLACK);
				resetAllColorButton();
				ib_black.setImageResource(drawable.icon_black_pressed);
			}
		});
		ib_blue.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				SoundPlayer.playSound(R.raw.keypress_common);
				//mplayerTool.playButtonPressed(DrawingActivity.this);
				dp_draw.setPaintColor(Color.BLUE);
				resetAllColorButton();
				ib_blue.setImageResource(drawable.icon_blue_pressed);
			}
		});
		ib_green.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				SoundPlayer.playSound(R.raw.keypress_common);
				//mplayerTool.playButtonPressed(DrawingActivity.this);
				dp_draw.setPaintColor(Color.GREEN);
				resetAllColorButton();
				ib_green.setImageResource(drawable.icon_green_pressed);
			}
		});
		ib_red.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				SoundPlayer.playSound(R.raw.keypress_common);
				//mplayerTool.playButtonPressed(DrawingActivity.this);
				dp_draw.setPaintColor(Color.RED);
				resetAllColorButton();
				ib_red.setImageResource(drawable.icon_red_pressed);
			}

		});
		ib_yellow.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				SoundPlayer.playSound(R.raw.keypress_common);
				//mplayerTool.playButtonPressed(DrawingActivity.this);
				dp_draw.setPaintColor(Color.YELLOW);
				resetAllColorButton();
				ib_yellow.setImageResource(drawable.icon_yellow_pressed);
			}
		});
		ib_eraser.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				SoundPlayer.playSound(R.raw.keypress_common);
				//mplayerTool.playButtonPressed(DrawingActivity.this);
				dp_draw.setPaintColor(Color.WHITE);
				resetAllColorButton();
				resetAllToolButton();
				ib_eraser.setImageResource(drawable.icon_eraser_pressed);
			}
		});
		ib_pencil.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				SoundPlayer.playSound(R.raw.keypress_common);
				//mplayerTool.playButtonPressed(DrawingActivity.this);
				if (dp_draw.getPaintColor() == Color.WHITE) {
					dp_draw.setPaintColor(Color.BLACK);
					resetAllColorButton();
					resetAllToolButton();
					ib_pencil.setImageResource(drawable.icon_pencil_pressed);
					ib_black.setImageResource(drawable.icon_black_pressed);
				}
			}
		});
		ib_small.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				SoundPlayer.playSound(R.raw.keypress_common);
				//mplayerTool.playButtonPressed(DrawingActivity.this);
				dp_draw.setStrokeWidth(6f);
				resetAllSizeButton();
				ib_small.setImageResource(drawable.icon_sizesmall_pressed);
			}
		});
		ib_medium.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				SoundPlayer.playSound(R.raw.keypress_common);
				//mplayerTool.playButtonPressed(DrawingActivity.this);
				dp_draw.setStrokeWidth(16f);
				resetAllSizeButton();
				ib_medium.setImageResource(drawable.icon_sizemedium_pressed);
			}
		});
		ib_large.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				SoundPlayer.playSound(R.raw.keypress_common);
				//mplayerTool.playButtonPressed(DrawingActivity.this);
				dp_draw.setStrokeWidth(36f);
				resetAllSizeButton();
				ib_large.setImageResource(drawable.icon_sizelarge_pressed);
			}
		});
		ib_clear.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				SoundPlayer.playSound(R.raw.keypress_common);
				//mplayerTool.playButtonPressed(DrawingActivity.this);
				dp_draw.clear();
			}
		});
	}

	private void resetAllColorButton() {
		ib_black.setImageResource(drawable.icon_black);
		ib_red.setImageResource(drawable.icon_red);
		ib_blue.setImageResource(drawable.icon_blue);
		ib_yellow.setImageResource(drawable.icon_yellow);
		ib_green.setImageResource(drawable.icon_green);
	}

	private void resetAllSizeButton() {
		ib_large.setImageResource(drawable.icon_sizelarge);
		ib_medium.setImageResource(drawable.icon_sizemedium);
		ib_small.setImageResource(drawable.icon_sizesmall);
	}

	private void resetAllToolButton() {
		ib_pencil.setImageResource(drawable.icon_pencil);
		ib_eraser.setImageResource(drawable.icon_eraser);
	}

	@Override
	protected void onResume() {
		super.onResume();
		SoundPlayer.start_p_drawing_music();
	}

	@Override
	protected void onPause() {
		super.onPause();
		SoundPlayer.pause_p_drawing_music();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		countDown.cancel();
	}

	void saveImage() {
		Bitmap mBitmap;
		dp_draw.setDrawingCacheEnabled(true);
		dp_draw.buildDrawingCache();
		mBitmap = dp_draw.getDrawingCache();
		String bmpStr = BitmapTool.bitMapToString(mBitmap);

		new DrawingSendTask().execute(et_word.getText().toString(), bmpStr);
	}

	private class DrawingSendTask extends AsyncTask<String, Void, String> {
		private AlertDialog_PG progressDialog;
		@Override
		protected void onPreExecute() {
			System.out.println("enter onPreExecute");
			countDown.cancel();
			progressDialog = DialogTool.showProgressDialog(DrawingActivity.this, "Sending question...");

		}

		@Override
		protected String doInBackground(String... arg) {// params = word, pic
			System.out.println("enter do in backGround");
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			MyApp myApp = (MyApp) getApplicationContext();
			params.add(new BasicNameValuePair("email", myApp.getUserEmail()));
			params.add(new BasicNameValuePair("roomname", myApp.getRoomName()));
			params.add(new BasicNameValuePair("word", arg[0].toUpperCase()));
			params.add(new BasicNameValuePair("pic", arg[1]));
			params.add(new BasicNameValuePair("MAC", myApp.getMac()));
			params.add(new BasicNameValuePair("ParamEnd",
					"ParamEndParamEndParamEnd"));
			return ConnectServer.connect(
					"http://" + ConnectServer.getServerAdd()
							+ "/game/send-question", params);
		}

		@Override
		protected void onPostExecute(String result) {
			DialogTool.cancelProgressDialog(progressDialog);
			if (!DialogTool.checkNetworkAlive(result, DrawingActivity.this,
					null))
				return;
			if (!DialogTool.checkLogin(result, DrawingActivity.this))
				return;

			String[] resultParam = result.split(",");

			// If success, go to game
			if ("OK".equals(resultParam[0])) {
				countDown.cancel();
				Intent intent = new Intent(DrawingActivity.this,
						ChallengerplayingActivity.class);
				intent.putExtra("role", "provider");
				startActivity(intent);
				//gen added
				SoundPlayer.stop_p_drawing_music();
				DrawingActivity.this.finish();
			}  else {
				DialogTool.showCustomMessage(DrawingActivity.this, result);
			}
		}

	}

	private class QuitDrawingTask extends AsyncTask<String, Void, String> {
		private AlertDialog_PG progressDialog;

		@Override
		protected void onPreExecute() {
			countDown.cancel();
			progressDialog = DialogTool.showProgressDialog(DrawingActivity.this, "Quitting...");
		}

		@Override
		protected String doInBackground(String... params) {
			List<BasicNameValuePair> connectParams = new ArrayList<BasicNameValuePair>();
			MyApp myApp = (MyApp) getApplicationContext();
			connectParams.add(new BasicNameValuePair("email", myApp
					.getUserEmail()));
			connectParams.add(new BasicNameValuePair("roomname", myApp
					.getRoomName()));
			connectParams.add(new BasicNameValuePair("MAC", myApp.getMac()));
			connectParams.add(new BasicNameValuePair("ParamEnd",
					"ParamEndParamEndParamEnd"));
			return ConnectServer.connect(
					"http://" + ConnectServer.getServerAdd()
							+ "/game/provider-quit", connectParams);
		}

		@Override
		protected void onPostExecute(String result) {
			DialogTool.cancelProgressDialog(progressDialog);
			if (!DialogTool.checkNetworkAlive(result, DrawingActivity.this,
					null))
				return;
			if (!DialogTool.checkLogin(result, DrawingActivity.this))
				return;
			String[] resultParam = result.split(",");

			// if success go to room list
			if ("OK".equals(resultParam[0])) {
				MiscTool.setMyAppQuitRoom(DrawingActivity.this);
				//Intent intent = new Intent(DrawingActivity.this,
				//		RoomlistActivity.class);
				//startActivity(intent);
				//gen added 
				SoundPlayer.stop_p_drawing_music();
				DrawingActivity.this.finish();
			} else
				DialogTool.showCustomMessage(DrawingActivity.this, result);
		}

	}

	private class DrawingTimeoutTask extends AsyncTask<String, Void, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			List<BasicNameValuePair> connectParams = new ArrayList<BasicNameValuePair>();
			MyApp myApp = (MyApp) getApplicationContext();
			connectParams.add(new BasicNameValuePair("email", myApp
					.getUserEmail()));
			connectParams.add(new BasicNameValuePair("roomname", myApp
					.getRoomName()));
			connectParams.add(new BasicNameValuePair("MAC", myApp.getMac()));
			connectParams.add(new BasicNameValuePair("ParamEnd",
					"ParamEndParamEndParamEnd"));
			return ConnectServer.connect(
					"http://" + ConnectServer.getServerAdd()
							+ "/game/drawing-timeout", connectParams);
		}

		@Override
		protected void onPostExecute(String result) {

			if (!DialogTool.checkNetworkAlive(result, DrawingActivity.this,
					null))
				return;
			if (!DialogTool.checkLogin(result, DrawingActivity.this))
				return;

			String[] resultParam = result.split(",");

			// if success go to room
			if ("OK".equals(resultParam[0])) {
				countDown.cancel();
				MiscTool.goToRoom(DrawingActivity.this, null);
				DrawingActivity.this.finish();
			} else {
				DialogTool.showCustomMessage(DrawingActivity.this, result);
			}

		}
	}
}
